package com.lt73.dynamicloader.controller;

import com.lt73.dynamicloader.loader.DynamicLoader;
import com.lt73.dynamicloader.loader.GatewayContext;
import com.lt73.dynamicloader.loader.MemoryClassLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: hanxiao
 * @Date: 2022/3/27 14:55
 */
@RestController
@RequestMapping("/dynamicloader")
public class DynamicLoaderTestController {


    private static String javaSrc = "public class TestClass{" +
            "public void sayHello(String msg) {" +
            "System.out.printf(\"Hello %s! This message from a Java String.%n\",msg);" +
            "}" +
            "public int add(int a,int b){" +
            "return a+b;" +
            "}" +
            "}";


    private static String javaSrcInterreptor =
            "import com.lt73.dynamicloader.loader.GatewayContext;\n" +
                    "import com.lt73.dynamicloader.loader.GatewayInterceptor;\n" +
                    "import lombok.extern.slf4j.Slf4j;\n" +
                    "import org.springframework.stereotype.Component;\n" +
                    "@Component\n" +
                    "@Slf4j\n" +
                    "public class TestIntercept implements GatewayInterceptor {\n" +
                    "    @Override\n" +
                    "    public void doInterceptor(GatewayContext gatewayContext) {\n" +
                    "        System.out.println(\"hanxiao\");\n" +
                    "    }\n" +
                    "}";

    @RequestMapping("/test")
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Map<String, byte[]> bytecode = DynamicLoader.compile("TestIntercept.java", javaSrcInterreptor);
        MemoryClassLoader classLoader = new MemoryClassLoader(bytecode);
        Class clazz = classLoader.loadClass("TestIntercept");
        Object object = clazz.newInstance();
        Method doInterceptor = clazz.getMethod("doInterceptor", GatewayContext.class);
        doInterceptor.invoke(object, new GatewayContext());

    }


    public void testCompile() {
        Map<String, byte[]> bytecode = DynamicLoader.compile("TestClass.java", javaSrc);
        for (Iterator<String> iterator = bytecode.keySet().iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            byte[] code = bytecode.get(key);
            System.out.printf("Class: %s, Length: %d%n", key, code.length);
        }
    }
}